package com.zjw.controller;

import com.zjw.annotation.SystemLog;
import com.zjw.annotation.domain.ResponseResult;
import com.zjw.annotation.domain.dto.AuditDto;
import com.zjw.annotation.domain.entity.Link;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.exception.SystemException;
import com.zjw.service.LinkService;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/content/link")
@PreAuthorize("@Ps.hasPermission('content:link:list')")
public class LinkController {

    @Autowired
    private LinkService linkService;

    @GetMapping("/list")
    @SystemLog("友联查询")
    @PreAuthorize("@Ps.hasPermission('content:link:query')")
    public ResponseResult getLinkList(Long pageNum,Long pageSize,
                                      String name, String status){
        return linkService.getLinkList(pageNum, pageSize, name, status);
    }


    @PostMapping()
    @SystemLog("新增友链")
    @PreAuthorize("@Ps.hasPermission('content:link:add')")
    public ResponseResult addLink(@RequestBody Link link){
        return linkService.addLink(link);
    }

    @GetMapping("/{id}")
    @SystemLog("更具id查询")
    @PreAuthorize("@Ps.hasPermission('content:link:query')")
    public ResponseResult queryLink(@PathVariable Long id){
        return linkService.getLinkById(id);
    }

    @PutMapping
    @SystemLog("更新友链")
    @PreAuthorize("@Ps.hasPermission('content:link:edit')")
    public ResponseResult editLink(@RequestBody Link link){
        return linkService.editLink(link);
    }

    @DeleteMapping("/{ids}")
    @SystemLog("删除友链")
    @PreAuthorize("@Ps.hasPermission('content:link:remove')")
    public ResponseResult removeLink(@PathVariable String ids){
        if(!Strings.hasText(ids))
            throw new SystemException(AppHttpCodeEnum.DATA_UNCOMPLETED);

        List<Long> idList = Arrays.stream(ids.split(",")).map(n -> Long.parseLong(n))
                .collect(Collectors.toList());
        return linkService.deleteLink(idList);
    }

//    审核状态更新
    @PutMapping("/changeLinkStatus")
    @PreAuthorize("@Ps.hasPermission('content:link:edit')")
    @SystemLog("审核按钮")
    public ResponseResult auditLink(@RequestBody AuditDto auditDto){

        return linkService.audit(auditDto.getId(), auditDto.getStatus());
    }

}
